package com.csproj.system.repository;



import com.csproj.system.domain.UserInfo;
import com.csproj.system.repository.custom.UserInfoRepositoryCustom;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;

import java.util.List;

/**
 * Spring Data JPA repository for the UserInfo entity.
 */
public interface UserInfoRepository extends JpaRepository<UserInfo,String> , UserInfoRepositoryCustom {

    @Query("select distinct userInfo from UserInfo userInfo left join fetch userInfo.roleInfos")
    List<UserInfo> findAllWithEagerRelationships();

    @Query("select userInfo from UserInfo userInfo left join fetch userInfo.roleInfos where userInfo.id =:id")
    UserInfo findOneWithEagerRelationships(@Param("id") String id);

    /**
     * 查询所有用户信息
     * @return
     */
    @Query(" from UserInfo ui where ui.deletedFlag = 0")
    List<UserInfo> findAll();

    /**
     * 根据账号查询用户
     * @param account   账号
     * @return
     */
    @Query(" from UserInfo ui where ui.deletedFlag = 0 and ui.account = ?1  ")
    UserInfo findByAccount(String account);

    /**
     * 根据账号查询可用用户
     * @return
     */
    @Query(" from UserInfo ui where ui.deletedFlag = 0 and ui.usedFlag = 1")
    List<UserInfo> findAllEnabled();

    /**
     * 根据手机号查询用户
     * @param phone   手机号
     * @return
     */
    @Query(" from UserInfo ui where ui.deletedFlag = 0 and ui.phone = ?1  ")
    UserInfo findByPhone(String phone);

    /**
     * 设置用户禁用
     * @param userInfoId    用户id
     * @return
     */
    @Modifying
    @Query(" update UserInfo ui set ui.usedFlag = 0 where ui.id = ?1")
    UserInfo setUserDisable(String userInfoId);

    /**
     * 设置用户启用
     * @param userInfoId    用户id
     * @return
    */
    @Modifying
    @Query(" update UserInfo ui set ui.usedFlag = 1 where ui.id = ?1")
    UserInfo setUserAble(String userInfoId);

    /**
     * 删除用户
     * @param UserInfoId    用户ID
     * @return
     */
    @Modifying
    @Query(" update UserInfo ui set ui.deletedFlag = 1 where ui.id = ?1")
    void deleteUserInfo(String UserInfoId);

    /**
     * 批量删除用户
     * @param ids   用户的ids
     * @return
     */
    @Modifying
    @Query(" update UserInfo set deletedFlag = 1 where id in (?1)")
    void deleteUserInfoIds(String[] ids) ;


    /**
     * 根据角色id查找  拥有该角色的用户信息
     * @param roleInfoId
     * @return
     */
    @Query(" select ui from UserInfo ui join ui.roleInfos as ri where ri.id = ?1")
    List<UserInfo> getUserInfoByRoleInfoId(String roleInfoId);


    /**
     * 根据ids查询机构信息
     * @author LM
     * @date   2017-12-04
     * @param ids
     * @return
     */
    @Query(" from UserInfo where deletedFlag = 0 and id in (?1) ")
    List<UserInfo> findByIds(String[] ids);

    /**
    获取站点下用户
     **/
    List<UserInfo> findAllBySiteIdAndDeletedFlagIsFalseAndUsedFlagIsTrue(String siteId);


}
